package com.kl.modular.system.service.impl;

import com.baomidou.mybatisplus.plugins.Page;
import com.kl.common.util.BeanMapperUtil;
import com.kl.modular.base.service.impl.BaseServiceImpl;
import com.kl.modular.system.dao.dto.SystemParamDto;
import com.kl.modular.system.dao.mapper.SystemParamMapper;
import com.kl.modular.system.dao.model.SystemArea;
import com.kl.modular.system.dao.model.SystemParam;
import com.kl.modular.system.service.api.ISystemAreaService;
import com.kl.modular.system.service.api.ISystemParamService;
import com.kl.modular.system.service.bo.SystemParamBo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;


/**
 * 系统参数serviceImpl业务实现
 * @author xr_zjb
 * @date 2017-08-09 13:48
 * @(C) xinrui Copyright 
 */
@Service
public class SystemParamServiceImpl extends BaseServiceImpl<SystemParamMapper, SystemParam> implements ISystemParamService {

    @Autowired
    private ISystemAreaService systemAreaService;

    /**
     * 系统参数分页
     * @param page 分页
     * @param paramBo
     * @return
     */
    public Page<SystemParam> selParamPagerByBo(Page<SystemParam> page, SystemParamBo paramBo) {
        SystemParamDto paramDto = BeanMapperUtil.map(paramBo, SystemParamDto.class);
        List<SystemParam> systemParams = baseMapper.selParamPagerByDto(page, paramDto);
        page.setRecords(systemParams);
        return page;
    }

    /**
     * 查找系统参数设置
     * @param dicTypeCode
     * @return
     */
    public String findSysParam(Long areaId, String dicTypeCode) {
        if(StringUtils.isEmpty(dicTypeCode)){
            return null;
        }
        SystemParamBo paramBo  = new SystemParamBo();
        paramBo.setDicTypeCode(dicTypeCode);
        SystemParamDto paramDto = BeanMapperUtil.map(paramBo, SystemParamDto.class);
        Page<SystemParam> page = new Page<SystemParam>();
        page.setSize(1);
        page.setCurrent(1);
        List<SystemParam> systemParams = baseMapper.selParamPagerByDto(page, paramDto);
        if(systemParams == null || systemParams.size() == 0){
            // 查找上级配置
            SystemArea systemArea = systemAreaService.selectById(areaId);
            if(systemArea == null || systemArea.getId().intValue() == 0){
                return null;
            }
            String dicValues = findSysParam(systemArea.getParentid(), dicTypeCode);
            return dicValues;
        }
        return systemParams.get(0).getSystemDic().getDicValue();
    }
}
